package com.android.settings.audio.peq.qr.encoder;


import static com.android.settings.audio.peq.qr.Constant.QR_SCHEMA_V1_EQ;

import android.text.TextUtils;


import com.android.settings.audio.peq.qr.QrManager;
import com.android.settings.audio.peq.qr.annotation.QrImpl;
import com.android.settings.audio.peq.soundeffect.PluginDataManager;
import com.android.settings.audio.peq.util.Base64;

import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;

/**
 * Created by We on 2023/5/25
 */
@QrImpl(id = QR_SCHEMA_V1_EQ)
public class EqV1Encoder extends QrManager.AbsEncoder {
    public EqV1Encoder() {
        this.id = QR_SCHEMA_V1_EQ; //by inject
    }

    @Override
    public String generateContent(byte[] data) {
        final StringBuilder sb = new StringBuilder(this.id);
        String eqDataBase64Str = Base64.encode(data);
        return sb.append(eqDataBase64Str).toString();
    }

    @Override
    public byte[] toBytes(Object dataEntity) throws Exception {
        PluginDataManager.EqData eqData = null;
        if (dataEntity instanceof PluginDataManager.EqData) {
            eqData = (PluginDataManager.EqData) dataEntity;
        }
        if (eqData == null) {
            throw new Exception("eqData is null");
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        String name = TextUtils.isEmpty(eqData.name) ? "" : eqData.name;
        byte[] nameBytes = name.getBytes();
        baos.write(nameBytes.length);
        baos.write(nameBytes);

        String device = TextUtils.isEmpty(eqData.device) ? "" : eqData.device;
        byte[] deviceBytes = device.getBytes();
        baos.write(deviceBytes.length);
        baos.write(deviceBytes);

        String description = TextUtils.isEmpty(eqData.description) ? "" : eqData.description;
        byte[] descriptionBytes = description.getBytes();
        baos.write(descriptionBytes.length);
        baos.write(descriptionBytes);

        float[] fs = eqData.value;
        baos.write(fs.length);//progresses 数量
        for (float v : fs) {
            baos.write(ByteBuffer.allocate(4).putFloat(v).array());
        }
        baos.close();
        return baos.toByteArray();
    }
}
